#!/usr/bin/env node
"use strict";
// node 内置文件模块
const fs = require("fs");

/**
 * 判读路径是否存在,如不存在创建文件夹
 * @param pathStr 参数要用path.join()拼接,项目下的相对路径
 * @return projectPath 返回绝对路径,可要可不要
 */
function mkdirPath(pathStr) {
  var projectPath = process.cwd()+'/src/views/';
  var tempDirArray = pathStr.split("/");
  // console.log('tempDirArray',tempDirArray);
  for (var i = 0; i < tempDirArray.length; i++) {
    projectPath = projectPath + "/" + tempDirArray[i];
    if (fs.existsSync(projectPath)) {
      continue;
    } else {
      fs.mkdirSync(projectPath);
    }
  }
  return projectPath;
}
module.exports = () => {
  const dirName = process.cwd();
  const action = process.argv[2];
  const type = process.argv[3];
  const fileName = process.argv[4];

  // console.log(`${action}  ${type} ${fileName}`);
  // console.log(dirName);

  if (action != "g" && action != "generate") {
    console.error("命令错误");
    process.exit();
  }
  const typeMap = {
    page: `${dirName}/src/views/${fileName}/index.vue`,
    component: "",
    directive: "",
    filter: "",
  };

  // 判断文件夹是否存在
  mkdirPath(fileName);
  fs.writeFile(
    typeMap[type],
    `
<template>
  <div></div>
</template> 
<script> 
export default {
  name:"${fileName}",
  data(){
    return {};
  },
  methods:{}
}
</script>
<style lang="less" scoped></style>`,
    (err) => {
      if (err) {
        console.error(err);
      } else {
        console.log("文件创建成功");
      }
    }
  );
};
